package http;

import java.io.*;
import java.net.URLDecoder;

/**
 * @author fengbo
 * @date 2018/10/20
 */
public class HttpRequest {

    private String url;
    private String host;

    public HttpRequest(String request) {
System.out.println(request);
        String[] headers = request.split("\r\n");
        setUrl(headers[0]);
        setHost(headers[1]);
    }

    public HttpRequest(InputStream input) {
        BufferedReader request = new BufferedReader(new InputStreamReader(input));
        init(request);
    }

    private void init(BufferedReader request) {
        try {
            setUrl(request.readLine());
            setHost(request.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setUrl(String line) {
        String[] split = line.split(" ");
        if (split.length > 2) {
            this.url = split[1];
        }
    }

    private void setHost(String line) {
        String[] split = line.split(": ");
        if (split.length >= 2 && "Host".equals(split[0])) {
            this.host = split[1];
        }
    }

    public String getUrl() {
        try {
            return URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getHost() {
        return host;
    }
}
